import { authenticateToken } from "../../../lib/auth.js";
import { getConnection } from "../../../lib/db.js";

const handler = async function handler(req, res) {
  try {
    const user = req.user;
    const { type } = req.query;
    const connection = await getConnection();

    if (req.method === "GET") {
      // 根据字典类型代码获取字典项
      const { include_disabled = "false", tree = "false" } = req.query;

      // 首先验证字典类型是否存在
      const [typeResult] = await connection.execute(
        "SELECT id, name FROM lookup_types WHERE code = ? AND tenant_id = ? AND status = 1",
        [type, user.tenant_id]
      );

      if (typeResult.length === 0) {
        return res.status(404).json({
          success: false,
          message: "字典类型不存在或已禁用",
        });
      }

      const typeId = typeResult[0].id;
      const typeName = typeResult[0].name;

      // 构建查询条件
      let whereClause = "WHERE type_id = ? AND tenant_id = ?";
      let queryParams = [typeId, user.tenant_id];

      if (include_disabled === "false") {
        whereClause += " AND status = 1";
      }

      const query = `
        SELECT id, parent_id, code, name, value, description, extra_data, 
               level, sort_order, status
        FROM lookup_items 
        ${whereClause}
        ORDER BY sort_order ASC, created_at ASC
      `;

      const [items] = await connection.execute(query, queryParams);

      // 解析 extra_data JSON
      const parsedItems = items.map((item) => ({
        ...item,
        extra_data: item.extra_data ? JSON.parse(item.extra_data) : null,
      }));

      let result;
      if (tree === "true") {
        // 构建树形结构
        result = buildTree(parsedItems);
      } else {
        // 返回扁平列表
        result = parsedItems;
      }

      res.status(200).json({
        success: true,
        data: {
          type_code: type,
          type_name: typeName,
          items: result,
        },
      });
    } else {
      res.status(405).json({
        success: false,
        message: "不支持的请求方法",
      });
    }
  } catch (error) {
    console.error("Lookup API error:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

export default authenticateToken(handler);

// 构建树形结构的辅助函数
function buildTree(items, parentId = null) {
  const result = [];

  for (const item of items) {
    if (item.parent_id === parentId) {
      const children = buildTree(items, item.id);
      const node = {
        ...item,
        children: children.length > 0 ? children : undefined,
      };
      result.push(node);
    }
  }

  return result;
}
